package com.inctech.clz2.test1;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class FivethQuestion {
	public String readFile() throws IOException{
		FileInputStream fis = new FileInputStream("words.txt");
		byte[] fileContends = new byte[fis.available()];
		fis.read(fileContends);
		String fileCont = new String(fileContends);
		fis.close();
		return fileCont;
	}
	
	public int wordsNum(String words) throws IOException{
		int length = words.length();
		int count = 0;
		for (int i = 0, j = readFile().length(); i < j; i++) {
			if(readFile().substring(i, i+length).equals(words)){
				count++;
			}
			if(i+length == readFile().length()){
				break;
			}
		}
		return count;
	}
	
	public String[] countThreeMax() throws IOException{
		List<String> list = new ArrayList<String>();
		FileReader fr = new FileReader("words.txt");
		BufferedReader br = new BufferedReader(fr);
		String str = "";
		while((str = br.readLine()) != null){
			String[] contends1 = str.split(" ");
			for (String string1 : contends1) {
				String[] contends2 = string1.split("[.]");
				for (String string2 : contends2) {
					String[] word = string2.split(",");
					for (String string3 : word) {
						list.add(string3);
					}
				}
			}
		}
		br.close();
		fr.close();
		Map<String,List<String>> word = list.stream().collect(Collectors.groupingBy((t)->((String)t)));
		String[] result = new String[3];
		word.forEach((everyWord,count)->{
			int wordCount = 0;
			if(word.get(everyWord).size() > wordCount){
				wordCount = word.get(everyWord).size();
				result[0] = everyWord;
			}
		});
		word.remove(result[0]);
		word.forEach((everyWord,count)->{
			int wordCount = 0;
			if(word.get(everyWord).size() > wordCount){
				wordCount = word.get(everyWord).size();
				result[1] = everyWord;
			}
		});
		word.remove(result[1]);
		word.forEach((everyWord,count)->{
			int wordCount = 0;
			if(word.get(everyWord).size() > wordCount){
				wordCount = word.get(everyWord).size();
				result[2] = everyWord;
			}
		});
		return result;
	}
}
